package com.quyunshuo.module.home.activity.login

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.quyunshuo.androidbaseframemvvm.base.ktx.launchIO
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.USER_INFO_DATA
import com.quyunshuo.androidbaseframemvvm.common.utils.ToastUtil
import com.quyunshuo.androidbaseframemvvm.network.bean.ArticleListRes2
import com.quyunshuo.androidbaseframemvvm.network.bean.UserInfo
import com.quyunshuo.module.home.activity.login.LoginRepository
import com.quyunshuo.module.home.provider.UserServiceProvider
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 首页的VM层
 *
 * @property mRepository HomeRepository 仓库层 通过Hilt注入
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:41 PM
 */
@HiltViewModel
class LoginViewModel @Inject constructor(private val mRepository: LoginRepository) :
    BaseViewModel() {

    private val TAG = "LoginViewModel"
    var loginLiveData: MutableLiveData<UserInfo> = MutableLiveData<UserInfo>()

    @Inject
    lateinit var repository: LoginRepository


    fun login(etUsername: String, etPassword: String) {
        launchIO {
            repository.login(etUsername, etPassword).catch {
                Log.d(TAG, "login catch: $it")
                ToastUtil.showToast("登录失败：$it")
            }.collect {
                //登录成功以后，我们需要保存一些信息？已经保存了cookie，为什么还需要呢？？？因为展示个人信息
                Log.d(TAG, "login collect: $it")
                if (it.data == null) {
                    ToastUtil.showToast("登录失败")
                    return@collect
                }
                UserServiceProvider.saveUserInfo(it.data)
                //页面如何关闭呢？？
                loginLiveData.postValue(it.data)
                ToastUtil.showToast("登录成功")

            }
        }
    }
}
